<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-divider v-if="isRecommend">为你推荐</van-divider>
      <!-- 商品列表 -->
      <div class="goods">
        <goodsitem
          v-for="item in goodsList"
          :key="item.id"
          id="goodslist"
          :describe="item.title"
          :price="item.market_price"
          :buy="item.buy"
          :url="item.img_url"
          @click="$router.push(`/particulars/${item.id}`)"
        ></goodsitem>
      </div>
      <van-divider v-if="isLoadDone || !isRecommend">已经全部加载</van-divider>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import _ from "lodash";
import { Toast } from "vant";
import { reqRecommend } from "@/api";
import goodsitem from "@/components/GoodsItem.vue";
import { ref, onMounted, onBeforeUnmount } from "vue";
let goodsList = ref([]);
let page = ref(1);
let pagesize = ref(10);
let isLoadDone = ref(false);
let isLoading = ref(false);
let isRecommend = ref(true);

const onRefresh = () => {
  setTimeout(async () => {
    Toast("刷新成功");
    isLoading.value = false;
    page.value++;
    let { message } = await reqRecommend(page.value, pagesize.value);
    if (message.length === 0) {
      Toast("没有更多");
      isRecommend.value = false;
    }
    goodsList.value = message;
  }, 1000);
};

const getGoodsList = async () => {
  let { message } = await reqRecommend(page.value, pagesize.value);
  goodsList.value = message;
};

const loadGoodsList = async () => {
  // 加载完成就不再触发滚动事件，不再触发请求
  if (isLoadDone.value) {
    return;
  }
  //滚上去的高度
  let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  //   网页视口的宽度
  let windowHeight =
    document.documentElement.clientHeight || document.body.clientHeight;
  //整个页面的高度
  let pageHeight =
    document.documentElement.scrollHeight || document.body.scrollHeight;

  if (Math.ceil(scrollTop) + windowHeight === pageHeight) {
    page.value++;
    let { message } = await reqRecommend(page.value, pagesize.value);
    // this.isLoadDone = false;
    if (message.length === 0) {
      // 说明数据加载完毕了
      isLoadDone.value = true;
      return;
    }
    goodsList.value = [...goodsList.value, ...message];
  }
};

const throttleLoadGoodsList = _.throttle(loadGoodsList, 300);

onMounted(() => {
  // 加载商品列表数据
  getGoodsList();
  // 给窗口绑定滚动事件
  window.addEventListener("scroll", throttleLoadGoodsList);
});

onBeforeUnmount(() => {
  // 给窗口绑定滚动事件
  window.removeEventListener("scroll", throttleLoadGoodsList);
});
</script>

<style lang="scss" scoped>
.goods {
  display: flex;
  flex-wrap: wrap;
  // justify-content: center;
  padding: 5px;

  #goodslist {
    margin: 5px;
  }
}

.van-divider {
  border-color: #c3c5c8;
}
</style>